home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / pickle.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2005-10-18  |  37.1 KB  |  1,416 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Create portable serialized representations of Python objects.
  5.  
  6. See module cPickle for a (much) faster implementation.
  7. See module copy_reg for a mechanism for registering custom picklers.
  8. See module pickletools source for extensive comments.
  9.  
  10. Classes:
  11.  
  12.     Pickler
  13.     Unpickler
  14.  
  15. Functions:
  16.  
  17.     dump(object, file)
  18.     dumps(object) -> string
  19.     load(file) -> object
  20.     loads(string) -> object
  21.  
  22. Misc variables:
  23.  
  24.     __version__
  25.     format_version
  26.     compatible_formats
  27.  
  28. '''
  29. __version__ = '$Revision: 1.158 $'
  30. from types import *
  31. from copy_reg import dispatch_table
  32. from copy_reg import _extension_registry, _inverted_registry, _extension_cache
  33. import marshal
  34. import sys
  35. import struct
  36. import re
  37. import warnings
  38. __all__ = [
  39.     'PickleError',
  40.     'PicklingError',
  41.     'UnpicklingError',
  42.     'Pickler',
  43.     'Unpickler',
  44.     'dump',
  45.     'dumps',
  46.     'load',
  47.     'loads']
  48. format_version = '2.0'
  49. compatible_formats = [
  50.     '1.0',
  51.     '1.1',
  52.     '1.2',
  53.     '1.3',
  54.     '2.0']
  55. HIGHEST_PROTOCOL = 2
  56. mloads = marshal.loads
  57.  
  58. class PickleError(Exception):
  59.     '''A common base class for the other pickling exceptions.'''
  60.     pass
  61.  
  62.  
  63. class PicklingError(PickleError):
  64.     '''This exception is raised when an unpicklable object is passed to the
  65.     dump() method.
  66.  
  67.     '''
  68.     pass
  69.  
  70.  
  71. class UnpicklingError(PickleError):
  72.     '''This exception is raised when there is a problem unpickling an object,
  73.     such as a security violation.
  74.  
  75.     Note that other exceptions may also be raised during unpickling, including
  76.     (but not necessarily limited to) AttributeError, EOFError, ImportError,
  77.     and IndexError.
  78.  
  79.     '''
  80.     pass
  81.  
  82.  
  83. class _Stop(Exception):
  84.     
  85.     def __init__(self, value):
  86.         self.value = value
  87.  
  88.  
  89.  
  90. try:
  91.     from org.python.core import PyStringMap
  92. except ImportError:
  93.     PyStringMap = None
  94.  
  95.  
  96. try:
  97.     UnicodeType
  98. except NameError:
  99.     UnicodeType = None
  100.  
  101. MARK = '('
  102. STOP = '.'
  103. POP = '0'
  104. POP_MARK = '1'
  105. DUP = '2'
  106. FLOAT = 'F'
  107. INT = 'I'
  108. BININT = 'J'
  109. BININT1 = 'K'
  110. LONG = 'L'
  111. BININT2 = 'M'
  112. NONE = 'N'
  113. PERSID = 'P'
  114. BINPERSID = 'Q'
  115. REDUCE = 'R'
  116. STRING = 'S'
  117. BINSTRING = 'T'
  118. SHORT_BINSTRING = 'U'
  119. UNICODE = 'V'
  120. BINUNICODE = 'X'
  121. APPEND = 'a'
  122. BUILD = 'b'
  123. GLOBAL = 'c'
  124. DICT = 'd'
  125. EMPTY_DICT = '}'
  126. APPENDS = 'e'
  127. GET = 'g'
  128. BINGET = 'h'
  129. INST = 'i'
  130. LONG_BINGET = 'j'
  131. LIST = 'l'
  132. EMPTY_LIST = ']'
  133. OBJ = 'o'
  134. PUT = 'p'
  135. BINPUT = 'q'
  136. LONG_BINPUT = 'r'
  137. SETITEM = 's'
  138. TUPLE = 't'
  139. EMPTY_TUPLE = ')'
  140. SETITEMS = 'u'
  141. BINFLOAT = 'G'
  142. TRUE = 'I01\n'
  143. FALSE = 'I00\n'
  144. PROTO = '\x80'
  145. NEWOBJ = '\x81'
  146. EXT1 = '\x82'
  147. EXT2 = '\x83'
  148. EXT4 = '\x84'
  149. TUPLE1 = '\x85'
  150. TUPLE2 = '\x86'
  151. TUPLE3 = '\x87'
  152. NEWTRUE = '\x88'
  153. NEWFALSE = '\x89'
  154. LONG1 = '\x8a'
  155. LONG4 = '\x8b'
  156. _tuplesize2code = [
  157.     EMPTY_TUPLE,
  158.     TUPLE1,
  159.     TUPLE2,
  160.     TUPLE3]
  161. []([] if re.match('[A-Z][A-Z0-9_]+$', x) else _[1])
  162. del x
  163.  
  164. class Pickler:
  165.     
  166.     def __init__(self, file, protocol = None, bin = None):
  167.         '''This takes a file-like object for writing a pickle data stream.
  168.  
  169.         The optional protocol argument tells the pickler to use the
  170.         given protocol; supported protocols are 0, 1, 2.  The default
  171.         protocol is 0, to be backwards compatible.  (Protocol 0 is the
  172.         only protocol that can be written to a file opened in text
  173.         mode and read back successfully.  When using a protocol higher
  174.         than 0, make sure the file is opened in binary mode, both when
  175.         pickling and unpickling.)
  176.  
  177.         Protocol 1 is more efficient than protocol 0; protocol 2 is
  178.         more efficient than protocol 1.
  179.  
  180.         Specifying a negative protocol version selects the highest
  181.         protocol version supported.  The higher the protocol used, the
  182.         more recent the version of Python needed to read the pickle
  183.         produced.
  184.  
  185.         The file parameter must have a write() method that accepts a single
  186.         string argument.  It can thus be an open file object, a StringIO
  187.         object, or any other custom object that meets this interface.
  188.  
  189.         '''
  190.         if protocol is not None and bin is not None:
  191.             raise ValueError, "can't specify both 'protocol' and 'bin'"
  192.         
  193.         if bin is not None:
  194.             warnings.warn("The 'bin' argument to Pickler() is deprecated", DeprecationWarning)
  195.             protocol = bin
  196.         
  197.         if protocol is None:
  198.             protocol = 0
  199.         
  200.         if protocol < 0:
  201.             protocol = HIGHEST_PROTOCOL
  202.         elif protocol <= protocol:
  203.             pass
  204.         elif not protocol <= HIGHEST_PROTOCOL:
  205.             raise ValueError('pickle protocol must be <= %d' % HIGHEST_PROTOCOL)
  206.         
  207.         self.write = file.write
  208.         self.memo = { }
  209.         self.proto = int(protocol)
  210.         self.bin = protocol >= 1
  211.         self.fast = 0
  212.  
  213.     
  214.     def clear_memo(self):
  215.         '''Clears the pickler\'s "memo".
  216.  
  217.         The memo is the data structure that remembers which objects the
  218.         pickler has already seen, so that shared or recursive objects are
  219.         pickled by reference and not by value.  This method is useful when
  220.         re-using picklers.
  221.  
  222.         '''
  223.         self.memo.clear()
  224.  
  225.     
  226.     def dump(self, obj):
  227.         '''Write a pickled representation of obj to the open file.'''
  228.         if self.proto >= 2:
  229.             self.write(PROTO + chr(self.proto))
  230.         
  231.         self.save(obj)
  232.         self.write(STOP)
  233.  
  234.     
  235.     def memoize(self, obj):
  236.         '''Store an object in the memo.'''
  237.         if self.fast:
  238.             return None
  239.         
  240.         if not id(obj) not in self.memo:
  241.             raise AssertionError
  242.         memo_len = len(self.memo)
  243.         self.write(self.put(memo_len))
  244.         self.memo[id(obj)] = (memo_len, obj)
  245.  
  246.     
  247.     def put(self, i, pack = struct.pack):
  248.         if self.bin:
  249.             if i < 256:
  250.                 return BINPUT + chr(i)
  251.             else:
  252.                 return LONG_BINPUT + pack('<i', i)
  253.         
  254.         return PUT + repr(i) + '\n'
  255.  
  256.     
  257.     def get(self, i, pack = struct.pack):
  258.         if self.bin:
  259.             if i < 256:
  260.                 return BINGET + chr(i)
  261.             else:
  262.                 return LONG_BINGET + pack('<i', i)
  263.         
  264.         return GET + repr(i) + '\n'
  265.  
  266.     
  267.     def save(self, obj):
  268.         pid = self.persistent_id(obj)
  269.         if pid:
  270.             self.save_pers(pid)
  271.             return None
  272.         
  273.         x = self.memo.get(id(obj))
  274.         if x:
  275.             self.write(self.get(x[0]))
  276.             return None
  277.         
  278.         t = type(obj)
  279.         f = self.dispatch.get(t)
  280.         if f:
  281.             f(self, obj)
  282.             return None
  283.         
  284.         
  285.         try:
  286.             issc = issubclass(t, TypeType)
  287.         except TypeError:
  288.             issc = 0
  289.  
  290.         if issc:
  291.             self.save_global(obj)
  292.             return None
  293.         
  294.         reduce = dispatch_table.get(t)
  295.         if reduce:
  296.             rv = reduce(obj)
  297.         else:
  298.             reduce = getattr(obj, '__reduce_ex__', None)
  299.             if reduce:
  300.                 rv = reduce(self.proto)
  301.             else:
  302.                 reduce = getattr(obj, '__reduce__', None)
  303.                 if reduce:
  304.                     rv = reduce()
  305.                 else:
  306.                     raise PicklingError("Can't pickle %r object: %r" % (t.__name__, obj))
  307.         if type(rv) is StringType:
  308.             self.save_global(obj, rv)
  309.             return None
  310.         
  311.         if type(rv) is not TupleType:
  312.             raise PicklingError('%s must return string or tuple' % reduce)
  313.         
  314.         l = len(rv)
  315.         if l <= l:
  316.             pass
  317.         elif not l <= 5:
  318.             raise PicklingError('Tuple returned by %s must have two to five elements' % reduce)
  319.         
  320.         self.save_reduce(obj = obj, *rv)
  321.  
  322.     
  323.     def persistent_id(self, obj):
  324.         pass
  325.  
  326.     
  327.     def save_pers(self, pid):
  328.         if self.bin:
  329.             self.save(pid)
  330.             self.write(BINPERSID)
  331.         else:
  332.             self.write(PERSID + str(pid) + '\n')
  333.  
  334.     
  335.     def save_reduce(self, func, args, state = None, listitems = None, dictitems = None, obj = None):
  336.         if not isinstance(args, TupleType):
  337.             if args is None:
  338.                 warnings.warn('__basicnew__ special case is deprecated', DeprecationWarning)
  339.             else:
  340.                 raise PicklingError('args from reduce() should be a tuple')
  341.         
  342.         if not callable(func):
  343.             raise PicklingError('func from reduce should be callable')
  344.         
  345.         save = self.save
  346.         write = self.write
  347.         if self.proto >= 2 and getattr(func, '__name__', '') == '__newobj__':
  348.             cls = args[0]
  349.             if not hasattr(cls, '__new__'):
  350.                 raise PicklingError('args[0] from __newobj__ args has no __new__')
  351.             
  352.             if obj is not None and cls is not obj.__class__:
  353.                 raise PicklingError('args[0] from __newobj__ args has the wrong class')
  354.             
  355.             args = args[1:]
  356.             save(cls)
  357.             save(args)
  358.             write(NEWOBJ)
  359.         else:
  360.             save(func)
  361.             save(args)
  362.             write(REDUCE)
  363.         if obj is not None:
  364.             self.memoize(obj)
  365.         
  366.         if listitems is not None:
  367.             self._batch_appends(listitems)
  368.         
  369.         if dictitems is not None:
  370.             self._batch_setitems(dictitems)
  371.         
  372.         if state is not None:
  373.             save(state)
  374.             write(BUILD)
  375.         
  376.  
  377.     dispatch = { }
  378.     
  379.     def save_none(self, obj):
  380.         self.write(NONE)
  381.  
  382.     dispatch[NoneType] = save_none
  383.     
  384.     def save_bool(self, obj):
  385.         if self.proto >= 2:
  386.             if not obj or NEWTRUE:
  387.                 pass
  388.             self.write(NEWFALSE)
  389.         elif not obj or TRUE:
  390.             pass
  391.         self.write(FALSE)
  392.  
  393.     dispatch[bool] = save_bool
  394.     
  395.     def save_int(self, obj, pack = struct.pack):
  396.         if self.bin:
  397.             if obj >= 0:
  398.                 if obj <= 255:
  399.                     self.write(BININT1 + chr(obj))
  400.                     return None
  401.                 
  402.                 if obj <= 65535:
  403.                     self.write('%c%c%c' % (BININT2, obj & 255, obj >> 8))
  404.                     return None
  405.                 
  406.             
  407.             high_bits = obj >> 31
  408.             if high_bits == 0 or high_bits == -1:
  409.                 self.write(BININT + pack('<i', obj))
  410.                 return None
  411.             
  412.         
  413.         self.write(INT + repr(obj) + '\n')
  414.  
  415.     dispatch[IntType] = save_int
  416.     
  417.     def save_long(self, obj, pack = struct.pack):
  418.         if self.proto >= 2:
  419.             bytes = encode_long(obj)
  420.             n = len(bytes)
  421.             if n < 256:
  422.                 self.write(LONG1 + chr(n) + bytes)
  423.             else:
  424.                 self.write(LONG4 + pack('<i', n) + bytes)
  425.             return None
  426.         
  427.         self.write(LONG + repr(obj) + '\n')
  428.  
  429.     dispatch[LongType] = save_long
  430.     
  431.     def save_float(self, obj, pack = struct.pack):
  432.         if self.bin:
  433.             self.write(BINFLOAT + pack('>d', obj))
  434.         else:
  435.             self.write(FLOAT + repr(obj) + '\n')
  436.  
  437.     dispatch[FloatType] = save_float
  438.     
  439.     def save_string(self, obj, pack = struct.pack):
  440.         if self.bin:
  441.             n = len(obj)
  442.             if n < 256:
  443.                 self.write(SHORT_BINSTRING + chr(n) + obj)
  444.             else:
  445.                 self.write(BINSTRING + pack('<i', n) + obj)
  446.         else:
  447.             self.write(STRING + repr(obj) + '\n')
  448.         self.memoize(obj)
  449.  
  450.     dispatch[StringType] = save_string
  451.     
  452.     def save_unicode(self, obj, pack = struct.pack):
  453.         if self.bin:
  454.             encoding = obj.encode('utf-8')
  455.             n = len(encoding)
  456.             self.write(BINUNICODE + pack('<i', n) + encoding)
  457.         else:
  458.             obj = obj.replace('\\', '\\u005c')
  459.             obj = obj.replace('\n', '\\u000a')
  460.             self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
  461.         self.memoize(obj)
  462.  
  463.     dispatch[UnicodeType] = save_unicode
  464.     if StringType == UnicodeType:
  465.         
  466.         def save_string(self, obj, pack = struct.pack):
  467.             unicode = obj.isunicode()
  468.             if self.bin:
  469.                 if unicode:
  470.                     obj = obj.encode('utf-8')
  471.                 
  472.                 l = len(obj)
  473.                 if l < 256 and not unicode:
  474.                     self.write(SHORT_BINSTRING + chr(l) + obj)
  475.                 else:
  476.                     s = pack('<i', l)
  477.                     if unicode:
  478.                         self.write(BINUNICODE + s + obj)
  479.                     else:
  480.                         self.write(BINSTRING + s + obj)
  481.             elif unicode:
  482.                 obj = obj.replace('\\', '\\u005c')
  483.                 obj = obj.replace('\n', '\\u000a')
  484.                 obj = obj.encode('raw-unicode-escape')
  485.                 self.write(UNICODE + obj + '\n')
  486.             else:
  487.                 self.write(STRING + repr(obj) + '\n')
  488.             self.memoize(obj)
  489.  
  490.         dispatch[StringType] = save_string
  491.     
  492.     
  493.     def save_tuple(self, obj):
  494.         write = self.write
  495.         proto = self.proto
  496.         n = len(obj)
  497.         if n == 0:
  498.             if proto:
  499.                 write(EMPTY_TUPLE)
  500.             else:
  501.                 write(MARK + TUPLE)
  502.             return None
  503.         
  504.         save = self.save
  505.         memo = self.memo
  506.         if n <= 3 and proto >= 2:
  507.             for element in obj:
  508.                 save(element)
  509.             
  510.             if id(obj) in memo:
  511.                 get = self.get(memo[id(obj)][0])
  512.                 write(POP * n + get)
  513.             else:
  514.                 write(_tuplesize2code[n])
  515.                 self.memoize(obj)
  516.             return None
  517.         
  518.         write(MARK)
  519.         for element in obj:
  520.             save(element)
  521.         
  522.         if id(obj) in memo:
  523.             get = self.get(memo[id(obj)][0])
  524.             if proto:
  525.                 write(POP_MARK + get)
  526.             else:
  527.                 write(POP * (n + 1) + get)
  528.             return None
  529.         
  530.         self.write(TUPLE)
  531.         self.memoize(obj)
  532.  
  533.     dispatch[TupleType] = save_tuple
  534.     
  535.     def save_empty_tuple(self, obj):
  536.         self.write(EMPTY_TUPLE)
  537.  
  538.     
  539.     def save_list(self, obj):
  540.         write = self.write
  541.         if self.bin:
  542.             write(EMPTY_LIST)
  543.         else:
  544.             write(MARK + LIST)
  545.         self.memoize(obj)
  546.         self._batch_appends(iter(obj))
  547.  
  548.     dispatch[ListType] = save_list
  549.     _BATCHSIZE = 1000
  550.     
  551.     def _batch_appends(self, items):
  552.         save = self.save
  553.         write = self.write
  554.         if not self.bin:
  555.             for x in items:
  556.                 save(x)
  557.                 write(APPEND)
  558.             
  559.             return None
  560.         
  561.         r = xrange(self._BATCHSIZE)
  562.         while items is not None:
  563.             tmp = []
  564.             for i in r:
  565.                 
  566.                 try:
  567.                     x = items.next()
  568.                     tmp.append(x)
  569.                 continue
  570.                 except StopIteration:
  571.                     items = None
  572.                     break
  573.                     continue
  574.                 
  575.  
  576.             
  577.             n = len(tmp)
  578.             if n > 1:
  579.                 write(MARK)
  580.                 for x in tmp:
  581.                     save(x)
  582.                 
  583.                 write(APPENDS)
  584.                 continue
  585.             None<EXCEPTION MATCH>StopIteration
  586.             if n:
  587.                 save(tmp[0])
  588.                 write(APPEND)
  589.                 continue
  590.  
  591.     
  592.     def save_dict(self, obj):
  593.         write = self.write
  594.         if self.bin:
  595.             write(EMPTY_DICT)
  596.         else:
  597.             write(MARK + DICT)
  598.         self.memoize(obj)
  599.         self._batch_setitems(obj.iteritems())
  600.  
  601.     dispatch[DictionaryType] = save_dict
  602.     if PyStringMap is not None:
  603.         dispatch[PyStringMap] = save_dict
  604.     
  605.     
  606.     def _batch_setitems(self, items):
  607.         save = self.save
  608.         write = self.write
  609.         if not self.bin:
  610.             for k, v in items:
  611.                 save(k)
  612.                 save(v)
  613.                 write(SETITEM)
  614.             
  615.             return None
  616.         
  617.         r = xrange(self._BATCHSIZE)
  618.         while items is not None:
  619.             tmp = []
  620.             for i in r:
  621.                 
  622.                 try:
  623.                     tmp.append(items.next())
  624.                 continue
  625.                 except StopIteration:
  626.                     items = None
  627.                     break
  628.                     continue
  629.                 
  630.  
  631.             
  632.             n = len(tmp)
  633.             if n > 1:
  634.                 write(MARK)
  635.                 for k, v in tmp:
  636.                     save(k)
  637.                     save(v)
  638.                 
  639.                 write(SETITEMS)
  640.                 continue
  641.             None<EXCEPTION MATCH>StopIteration
  642.             if n:
  643.                 (k, v) = tmp[0]
  644.                 save(k)
  645.                 save(v)
  646.                 write(SETITEM)
  647.                 continue
  648.  
  649.     
  650.     def save_inst(self, obj):
  651.         cls = obj.__class__
  652.         memo = self.memo
  653.         write = self.write
  654.         save = self.save
  655.         if hasattr(obj, '__getinitargs__'):
  656.             args = obj.__getinitargs__()
  657.             len(args)
  658.             _keep_alive(args, memo)
  659.         else:
  660.             args = ()
  661.         write(MARK)
  662.         if self.bin:
  663.             save(cls)
  664.             for arg in args:
  665.                 save(arg)
  666.             
  667.             write(OBJ)
  668.         else:
  669.             for arg in args:
  670.                 save(arg)
  671.             
  672.             write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
  673.         self.memoize(obj)
  674.         
  675.         try:
  676.             getstate = obj.__getstate__
  677.         except AttributeError:
  678.             stuff = obj.__dict__
  679.  
  680.         stuff = getstate()
  681.         _keep_alive(stuff, memo)
  682.         save(stuff)
  683.         write(BUILD)
  684.  
  685.     dispatch[InstanceType] = save_inst
  686.     
  687.     def save_global(self, obj, name = None, pack = struct.pack):
  688.         write = self.write
  689.         memo = self.memo
  690.         if name is None:
  691.             name = obj.__name__
  692.         
  693.         module = getattr(obj, '__module__', None)
  694.         if module is None:
  695.             module = whichmodule(obj, name)
  696.         
  697.         
  698.         try:
  699.             __import__(module)
  700.             mod = sys.modules[module]
  701.             klass = getattr(mod, name)
  702.         except (ImportError, KeyError, AttributeError):
  703.             raise PicklingError("Can't pickle %r: it's not found as %s.%s" % (obj, module, name))
  704.  
  705.         if klass is not obj:
  706.             raise PicklingError("Can't pickle %r: it's not the same object as %s.%s" % (obj, module, name))
  707.         
  708.         if self.proto >= 2:
  709.             code = _extension_registry.get((module, name))
  710.             if code:
  711.                 if not code > 0:
  712.                     raise AssertionError
  713.                 if code <= 255:
  714.                     write(EXT1 + chr(code))
  715.                 elif code <= 65535:
  716.                     write('%c%c%c' % (EXT2, code & 255, code >> 8))
  717.                 else:
  718.                     write(EXT4 + pack('<i', code))
  719.                 return None
  720.             
  721.         
  722.         write(GLOBAL + module + '\n' + name + '\n')
  723.         self.memoize(obj)
  724.  
  725.     dispatch[ClassType] = save_global
  726.     dispatch[FunctionType] = save_global
  727.     dispatch[BuiltinFunctionType] = save_global
  728.     dispatch[TypeType] = save_global
  729.  
  730.  
  731. def _keep_alive(x, memo):
  732.     '''Keeps a reference to the object x in the memo.
  733.  
  734.     Because we remember objects by their id, we have
  735.     to assure that possibly temporary objects are kept
  736.     alive by referencing them.
  737.     We store a reference at the id of the memo, which should
  738.     normally not be used unless someone tries to deepcopy
  739.     the memo itself...
  740.     '''
  741.     
  742.     try:
  743.         memo[id(memo)].append(x)
  744.     except KeyError:
  745.         memo[id(memo)] = [
  746.             x]
  747.  
  748.  
  749. classmap = { }
  750.  
  751. def whichmodule(func, funcname):
  752.     '''Figure out the module in which a function occurs.
  753.  
  754.     Search sys.modules for the module.
  755.     Cache in classmap.
  756.     Return a module name.
  757.     If the function cannot be found, return "__main__".
  758.     '''
  759.     mod = getattr(func, '__module__', None)
  760.     if mod is not None:
  761.         return mod
  762.     
  763.     if func in classmap:
  764.         return classmap[func]
  765.     
  766.     for name, module in sys.modules.items():
  767.         if module is None:
  768.             continue
  769.         
  770.         if name != '__main__' and getattr(module, funcname, None) is func:
  771.             break
  772.             continue
  773.     else:
  774.         name = '__main__'
  775.     classmap[func] = name
  776.     return name
  777.  
  778.  
  779. class Unpickler:
  780.     
  781.     def __init__(self, file):
  782.         '''This takes a file-like object for reading a pickle data stream.
  783.  
  784.         The protocol version of the pickle is detected automatically, so no
  785.         proto argument is needed.
  786.  
  787.         The file-like object must have two methods, a read() method that
  788.         takes an integer argument, and a readline() method that requires no
  789.         arguments.  Both methods should return a string.  Thus file-like
  790.         object can be a file object opened for reading, a StringIO object,
  791.         or any other custom object that meets this interface.
  792.         '''
  793.         self.readline = file.readline
  794.         self.read = file.read
  795.         self.memo = { }
  796.  
  797.     
  798.     def load(self):
  799.         '''Read a pickled object representation from the open file.
  800.  
  801.         Return the reconstituted object hierarchy specified in the file.
  802.         '''
  803.         self.mark = object()
  804.         self.stack = []
  805.         self.append = self.stack.append
  806.         read = self.read
  807.         dispatch = self.dispatch
  808.         
  809.         try:
  810.             while None:
  811.                 key = read(1)
  812.         except _Stop:
  813.             stopinst = None
  814.             return stopinst.value
  815.  
  816.  
  817.     
  818.     def marker(self):
  819.         stack = self.stack
  820.         mark = self.mark
  821.         k = len(stack) - 1
  822.         while stack[k] is not mark:
  823.             k = k - 1
  824.         return k
  825.  
  826.     dispatch = { }
  827.     
  828.     def load_eof(self):
  829.         raise EOFError
  830.  
  831.     dispatch[''] = load_eof
  832.     
  833.     def load_proto(self):
  834.         proto = ord(self.read(1))
  835.         if proto <= proto:
  836.             pass
  837.         elif not proto <= 2:
  838.             raise ValueError, 'unsupported pickle protocol: %d' % proto
  839.         
  840.  
  841.     dispatch[PROTO] = load_proto
  842.     
  843.     def load_persid(self):
  844.         pid = self.readline()[:-1]
  845.         self.append(self.persistent_load(pid))
  846.  
  847.     dispatch[PERSID] = load_persid
  848.     
  849.     def load_binpersid(self):
  850.         pid = self.stack.pop()
  851.         self.append(self.persistent_load(pid))
  852.  
  853.     dispatch[BINPERSID] = load_binpersid
  854.     
  855.     def load_none(self):
  856.         self.append(None)
  857.  
  858.     dispatch[NONE] = load_none
  859.     
  860.     def load_false(self):
  861.         self.append(False)
  862.  
  863.     dispatch[NEWFALSE] = load_false
  864.     
  865.     def load_true(self):
  866.         self.append(True)
  867.  
  868.     dispatch[NEWTRUE] = load_true
  869.     
  870.     def load_int(self):
  871.         data = self.readline()
  872.         if data == FALSE[1:]:
  873.             val = False
  874.         elif data == TRUE[1:]:
  875.             val = True
  876.         else:
  877.             
  878.             try:
  879.                 val = int(data)
  880.             except ValueError:
  881.                 val = long(data)
  882.  
  883.         self.append(val)
  884.  
  885.     dispatch[INT] = load_int
  886.     
  887.     def load_binint(self):
  888.         self.append(mloads('i' + self.read(4)))
  889.  
  890.     dispatch[BININT] = load_binint
  891.     
  892.     def load_binint1(self):
  893.         self.append(ord(self.read(1)))
  894.  
  895.     dispatch[BININT1] = load_binint1
  896.     
  897.     def load_binint2(self):
  898.         self.append(mloads('i' + self.read(2) + '\x00\x00'))
  899.  
  900.     dispatch[BININT2] = load_binint2
  901.     
  902.     def load_long(self):
  903.         self.append(long(self.readline()[:-1], 0))
  904.  
  905.     dispatch[LONG] = load_long
  906.     
  907.     def load_long1(self):
  908.         n = ord(self.read(1))
  909.         bytes = self.read(n)
  910.         self.append(decode_long(bytes))
  911.  
  912.     dispatch[LONG1] = load_long1
  913.     
  914.     def load_long4(self):
  915.         n = mloads('i' + self.read(4))
  916.         bytes = self.read(n)
  917.         self.append(decode_long(bytes))
  918.  
  919.     dispatch[LONG4] = load_long4
  920.     
  921.     def load_float(self):
  922.         self.append(float(self.readline()[:-1]))
  923.  
  924.     dispatch[FLOAT] = load_float
  925.     
  926.     def load_binfloat(self, unpack = struct.unpack):
  927.         self.append(unpack('>d', self.read(8))[0])
  928.  
  929.     dispatch[BINFLOAT] = load_binfloat
  930.     
  931.     def load_string(self):
  932.         rep = self.readline()[:-1]
  933.         for q in '"\'':
  934.             if rep.startswith(q):
  935.                 if not rep.endswith(q):
  936.                     raise ValueError, 'insecure string pickle'
  937.                 
  938.                 rep = rep[len(q):-len(q)]
  939.                 break
  940.                 continue
  941.         else:
  942.             raise ValueError, 'insecure string pickle'
  943.         self.append(rep.decode('string-escape'))
  944.  
  945.     dispatch[STRING] = load_string
  946.     
  947.     def load_binstring(self):
  948.         len = mloads('i' + self.read(4))
  949.         self.append(self.read(len))
  950.  
  951.     dispatch[BINSTRING] = load_binstring
  952.     
  953.     def load_unicode(self):
  954.         self.append(unicode(self.readline()[:-1], 'raw-unicode-escape'))
  955.  
  956.     dispatch[UNICODE] = load_unicode
  957.     
  958.     def load_binunicode(self):
  959.         len = mloads('i' + self.read(4))
  960.         self.append(unicode(self.read(len), 'utf-8'))
  961.  
  962.     dispatch[BINUNICODE] = load_binunicode
  963.     
  964.     def load_short_binstring(self):
  965.         len = ord(self.read(1))
  966.         self.append(self.read(len))
  967.  
  968.     dispatch[SHORT_BINSTRING] = load_short_binstring
  969.     
  970.     def load_tuple(self):
  971.         k = self.marker()
  972.         self.stack[k:] = [
  973.             tuple(self.stack[k + 1:])]
  974.  
  975.     dispatch[TUPLE] = load_tuple
  976.     
  977.     def load_empty_tuple(self):
  978.         self.stack.append(())
  979.  
  980.     dispatch[EMPTY_TUPLE] = load_empty_tuple
  981.     
  982.     def load_tuple1(self):
  983.         self.stack[-1] = (self.stack[-1],)
  984.  
  985.     dispatch[TUPLE1] = load_tuple1
  986.     
  987.     def load_tuple2(self):
  988.         self.stack[-2:] = [
  989.             (self.stack[-2], self.stack[-1])]
  990.  
  991.     dispatch[TUPLE2] = load_tuple2
  992.     
  993.     def load_tuple3(self):
  994.         self.stack[-3:] = [
  995.             (self.stack[-3], self.stack[-2], self.stack[-1])]
  996.  
  997.     dispatch[TUPLE3] = load_tuple3
  998.     
  999.     def load_empty_list(self):
  1000.         self.stack.append([])
  1001.  
  1002.     dispatch[EMPTY_LIST] = load_empty_list
  1003.     
  1004.     def load_empty_dictionary(self):
  1005.         self.stack.append({ })
  1006.  
  1007.     dispatch[EMPTY_DICT] = load_empty_dictionary
  1008.     
  1009.     def load_list(self):
  1010.         k = self.marker()
  1011.         self.stack[k:] = [
  1012.             self.stack[k + 1:]]
  1013.  
  1014.     dispatch[LIST] = load_list
  1015.     
  1016.     def load_dict(self):
  1017.         k = self.marker()
  1018.         d = { }
  1019.         items = self.stack[k + 1:]
  1020.         for i in range(0, len(items), 2):
  1021.             key = items[i]
  1022.             value = items[i + 1]
  1023.             d[key] = value
  1024.         
  1025.         self.stack[k:] = [
  1026.             d]
  1027.  
  1028.     dispatch[DICT] = load_dict
  1029.     
  1030.     def _instantiate(self, klass, k):
  1031.         args = tuple(self.stack[k + 1:])
  1032.         del self.stack[k:]
  1033.         instantiated = 0
  1034.         if not args and type(klass) is ClassType and not hasattr(klass, '__getinitargs__'):
  1035.             
  1036.             try:
  1037.                 value = _EmptyClass()
  1038.                 value.__class__ = klass
  1039.                 instantiated = 1
  1040.             except RuntimeError:
  1041.                 pass
  1042.             except:
  1043.                 None<EXCEPTION MATCH>RuntimeError
  1044.             
  1045.  
  1046.         None<EXCEPTION MATCH>RuntimeError
  1047.         if not instantiated:
  1048.             
  1049.             try:
  1050.                 value = klass(*args)
  1051.             except TypeError:
  1052.                 err = None
  1053.                 raise TypeError, 'in constructor for %s: %s' % (klass.__name__, str(err)), sys.exc_info()[2]
  1054.             except:
  1055.                 None<EXCEPTION MATCH>TypeError
  1056.             
  1057.  
  1058.         None<EXCEPTION MATCH>TypeError
  1059.         self.append(value)
  1060.  
  1061.     
  1062.     def load_inst(self):
  1063.         module = self.readline()[:-1]
  1064.         name = self.readline()[:-1]
  1065.         klass = self.find_class(module, name)
  1066.         self._instantiate(klass, self.marker())
  1067.  
  1068.     dispatch[INST] = load_inst
  1069.     
  1070.     def load_obj(self):
  1071.         k = self.marker()
  1072.         klass = self.stack.pop(k + 1)
  1073.         self._instantiate(klass, k)
  1074.  
  1075.     dispatch[OBJ] = load_obj
  1076.     
  1077.     def load_newobj(self):
  1078.         args = self.stack.pop()
  1079.         cls = self.stack[-1]
  1080.         obj = cls.__new__(cls, *args)
  1081.         self.stack[-1] = obj
  1082.  
  1083.     dispatch[NEWOBJ] = load_newobj
  1084.     
  1085.     def load_global(self):
  1086.         module = self.readline()[:-1]
  1087.         name = self.readline()[:-1]
  1088.         klass = self.find_class(module, name)
  1089.         self.append(klass)
  1090.  
  1091.     dispatch[GLOBAL] = load_global
  1092.     
  1093.     def load_ext1(self):
  1094.         code = ord(self.read(1))
  1095.         self.get_extension(code)
  1096.  
  1097.     dispatch[EXT1] = load_ext1
  1098.     
  1099.     def load_ext2(self):
  1100.         code = mloads('i' + self.read(2) + '\x00\x00')
  1101.         self.get_extension(code)
  1102.  
  1103.     dispatch[EXT2] = load_ext2
  1104.     
  1105.     def load_ext4(self):
  1106.         code = mloads('i' + self.read(4))
  1107.         self.get_extension(code)
  1108.  
  1109.     dispatch[EXT4] = load_ext4
  1110.     
  1111.     def get_extension(self, code):
  1112.         nil = []
  1113.         obj = _extension_cache.get(code, nil)
  1114.         if obj is not nil:
  1115.             self.append(obj)
  1116.             return None
  1117.         
  1118.         key = _inverted_registry.get(code)
  1119.         if not key:
  1120.             raise ValueError('unregistered extension code %d' % code)
  1121.         
  1122.         obj = self.find_class(*key)
  1123.         _extension_cache[code] = obj
  1124.         self.append(obj)
  1125.  
  1126.     
  1127.     def find_class(self, module, name):
  1128.         __import__(module)
  1129.         mod = sys.modules[module]
  1130.         klass = getattr(mod, name)
  1131.         return klass
  1132.  
  1133.     
  1134.     def load_reduce(self):
  1135.         stack = self.stack
  1136.         args = stack.pop()
  1137.         func = stack[-1]
  1138.         if args is None:
  1139.             warnings.warn('__basicnew__ special case is deprecated', DeprecationWarning)
  1140.             value = func.__basicnew__()
  1141.         else:
  1142.             value = func(*args)
  1143.         stack[-1] = value
  1144.  
  1145.     dispatch[REDUCE] = load_reduce
  1146.     
  1147.     def load_pop(self):
  1148.         del self.stack[-1]
  1149.  
  1150.     dispatch[POP] = load_pop
  1151.     
  1152.     def load_pop_mark(self):
  1153.         k = self.marker()
  1154.         del self.stack[k:]
  1155.  
  1156.     dispatch[POP_MARK] = load_pop_mark
  1157.     
  1158.     def load_dup(self):
  1159.         self.append(self.stack[-1])
  1160.  
  1161.     dispatch[DUP] = load_dup
  1162.     
  1163.     def load_get(self):
  1164.         self.append(self.memo[self.readline()[:-1]])
  1165.  
  1166.     dispatch[GET] = load_get
  1167.     
  1168.     def load_binget(self):
  1169.         i = ord(self.read(1))
  1170.         self.append(self.memo[repr(i)])
  1171.  
  1172.     dispatch[BINGET] = load_binget
  1173.     
  1174.     def load_long_binget(self):
  1175.         i = mloads('i' + self.read(4))
  1176.         self.append(self.memo[repr(i)])
  1177.  
  1178.     dispatch[LONG_BINGET] = load_long_binget
  1179.     
  1180.     def load_put(self):
  1181.         self.memo[self.readline()[:-1]] = self.stack[-1]
  1182.  
  1183.     dispatch[PUT] = load_put
  1184.     
  1185.     def load_binput(self):
  1186.         i = ord(self.read(1))
  1187.         self.memo[repr(i)] = self.stack[-1]
  1188.  
  1189.     dispatch[BINPUT] = load_binput
  1190.     
  1191.     def load_long_binput(self):
  1192.         i = mloads('i' + self.read(4))
  1193.         self.memo[repr(i)] = self.stack[-1]
  1194.  
  1195.     dispatch[LONG_BINPUT] = load_long_binput
  1196.     
  1197.     def load_append(self):
  1198.         stack = self.stack
  1199.         value = stack.pop()
  1200.         list = stack[-1]
  1201.         list.append(value)
  1202.  
  1203.     dispatch[APPEND] = load_append
  1204.     
  1205.     def load_appends(self):
  1206.         stack = self.stack
  1207.         mark = self.marker()
  1208.         list = stack[mark - 1]
  1209.         list.extend(stack[mark + 1:])
  1210.         del stack[mark:]
  1211.  
  1212.     dispatch[APPENDS] = load_appends
  1213.     
  1214.     def load_setitem(self):
  1215.         stack = self.stack
  1216.         value = stack.pop()
  1217.         key = stack.pop()
  1218.         dict = stack[-1]
  1219.         dict[key] = value
  1220.  
  1221.     dispatch[SETITEM] = load_setitem
  1222.     
  1223.     def load_setitems(self):
  1224.         stack = self.stack
  1225.         mark = self.marker()
  1226.         dict = stack[mark - 1]
  1227.         for i in range(mark + 1, len(stack), 2):
  1228.             dict[stack[i]] = stack[i + 1]
  1229.         
  1230.         del stack[mark:]
  1231.  
  1232.     dispatch[SETITEMS] = load_setitems
  1233.     
  1234.     def load_build(self):
  1235.         stack = self.stack
  1236.         state = stack.pop()
  1237.         inst = stack[-1]
  1238.         setstate = getattr(inst, '__setstate__', None)
  1239.         if setstate:
  1240.             setstate(state)
  1241.             return None
  1242.         
  1243.         slotstate = None
  1244.         if isinstance(state, tuple) and len(state) == 2:
  1245.             (state, slotstate) = state
  1246.         
  1247.         if state:
  1248.             
  1249.             try:
  1250.                 inst.__dict__.update(state)
  1251.             except RuntimeError:
  1252.                 for k, v in state.items():
  1253.                     setattr(inst, k, v)
  1254.                 
  1255.             
  1256.  
  1257.         None<EXCEPTION MATCH>RuntimeError
  1258.         if slotstate:
  1259.             for k, v in slotstate.items():
  1260.                 setattr(inst, k, v)
  1261.             
  1262.         
  1263.  
  1264.     dispatch[BUILD] = load_build
  1265.     
  1266.     def load_mark(self):
  1267.         self.append(self.mark)
  1268.  
  1269.     dispatch[MARK] = load_mark
  1270.     
  1271.     def load_stop(self):
  1272.         value = self.stack.pop()
  1273.         raise _Stop(value)
  1274.  
  1275.     dispatch[STOP] = load_stop
  1276.  
  1277.  
  1278. class _EmptyClass:
  1279.     pass
  1280.  
  1281. import binascii as _binascii
  1282.  
  1283. def encode_long(x):
  1284.     """Encode a long to a two's complement little-endian binary string.
  1285.     Note that 0L is a special case, returning an empty string, to save a
  1286.     byte in the LONG1 pickling context.
  1287.  
  1288.     >>> encode_long(0L)
  1289.     ''
  1290.     >>> encode_long(255L)
  1291.     '\\xff\\x00'
  1292.     >>> encode_long(32767L)
  1293.     '\\xff\\x7f'
  1294.     >>> encode_long(-256L)
  1295.     '\\x00\\xff'
  1296.     >>> encode_long(-32768L)
  1297.     '\\x00\\x80'
  1298.     >>> encode_long(-128L)
  1299.     '\\x80'
  1300.     >>> encode_long(127L)
  1301.     '\\x7f'
  1302.     >>>
  1303.     """
  1304.     if x == 0:
  1305.         return ''
  1306.     
  1307.     if x > 0:
  1308.         ashex = hex(x)
  1309.         if not ashex.startswith('0x'):
  1310.             raise AssertionError
  1311.         njunkchars = 2 + ashex.endswith('L')
  1312.         nibbles = len(ashex) - njunkchars
  1313.         if nibbles & 1:
  1314.             ashex = '0x0' + ashex[2:]
  1315.         elif int(ashex[2], 16) >= 8:
  1316.             ashex = '0x00' + ashex[2:]
  1317.         
  1318.     else:
  1319.         ashex = hex(-x)
  1320.         if not ashex.startswith('0x'):
  1321.             raise AssertionError
  1322.         njunkchars = 2 + ashex.endswith('L')
  1323.         nibbles = len(ashex) - njunkchars
  1324.         if nibbles & 1:
  1325.             nibbles += 1
  1326.         
  1327.         nbits = nibbles * 4
  1328.         x += 0x1L << nbits
  1329.         if not x > 0:
  1330.             raise AssertionError
  1331.         ashex = hex(x)
  1332.         njunkchars = 2 + ashex.endswith('L')
  1333.         newnibbles = len(ashex) - njunkchars
  1334.         if newnibbles < nibbles:
  1335.             ashex = '0x' + '0' * (nibbles - newnibbles) + ashex[2:]
  1336.         
  1337.         if int(ashex[2], 16) < 8:
  1338.             ashex = '0xff' + ashex[2:]
  1339.         
  1340.     if ashex.endswith('L'):
  1341.         ashex = ashex[2:-1]
  1342.     else:
  1343.         ashex = ashex[2:]
  1344.     if not len(ashex) & 1 == 0:
  1345.         raise AssertionError, (x, ashex)
  1346.     binary = _binascii.unhexlify(ashex)
  1347.     return binary[::-1]
  1348.  
  1349.  
  1350. def decode_long(data):
  1351.     '''Decode a long from a two\'s complement little-endian binary string.
  1352.  
  1353.     >>> decode_long(\'\')
  1354.     0L
  1355.     >>> decode_long("\\xff\\x00")
  1356.     255L
  1357.     >>> decode_long("\\xff\\x7f")
  1358.     32767L
  1359.     >>> decode_long("\\x00\\xff")
  1360.     -256L
  1361.     >>> decode_long("\\x00\\x80")
  1362.     -32768L
  1363.     >>> decode_long("\\x80")
  1364.     -128L
  1365.     >>> decode_long("\\x7f")
  1366.     127L
  1367.     '''
  1368.     nbytes = len(data)
  1369.     if nbytes == 0:
  1370.         return 0x0L
  1371.     
  1372.     ashex = _binascii.hexlify(data[::-1])
  1373.     n = long(ashex, 16)
  1374.     if data[-1] >= '\x80':
  1375.         n -= 0x1L << nbytes * 8
  1376.     
  1377.     return n
  1378.  
  1379.  
  1380. try:
  1381.     from cStringIO import StringIO
  1382. except ImportError:
  1383.     __all__.extend
  1384.     __all__.extend
  1385.     from StringIO import StringIO
  1386. except:
  1387.     __all__.extend
  1388.  
  1389.  
  1390. def dump(obj, file, protocol = None, bin = None):
  1391.     Pickler(file, protocol, bin).dump(obj)
  1392.  
  1393.  
  1394. def dumps(obj, protocol = None, bin = None):
  1395.     file = StringIO()
  1396.     Pickler(file, protocol, bin).dump(obj)
  1397.     return file.getvalue()
  1398.  
  1399.  
  1400. def load(file):
  1401.     return Unpickler(file).load()
  1402.  
  1403.  
  1404. def loads(str):
  1405.     file = StringIO(str)
  1406.     return Unpickler(file).load()
  1407.  
  1408.  
  1409. def _test():
  1410.     import doctest
  1411.     return doctest.testmod()
  1412.  
  1413. if __name__ == '__main__':
  1414.     _test()
  1415.  
  1416.